package com.shujia.flink.sink

import org.apache.flink.api.common.serialization.SimpleStringEncoder
import org.apache.flink.configuration.MemorySize
import org.apache.flink.connector.file.sink.FileSink
import org.apache.flink.core.fs.Path
import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.DefaultRollingPolicy
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}

import java.time.Duration

object Demo1FileSink {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    /**
     * 1、file sink ,将处理好的结果保存到文件中
     *
     */

    val sink: FileSink[String] = FileSink
      //指定数据保存的路径和格式
      .forRowFormat(new Path("data/flink_file_sink"), new SimpleStringEncoder[String]("UTF-8"))
      //指定滚动生成文件的策略
      .withRollingPolicy(
        DefaultRollingPolicy.builder()
          //滚动生成文件的时间间隔
          .withRolloverInterval(Duration.ofSeconds(10))
          //如果一段时间没有新的数据生成一个文件
          .withInactivityInterval(Duration.ofSeconds(10))
          //文件大小操作指定值生成新的文件
          .withMaxPartSize(MemorySize.ofMebiBytes(1))
          .build())
      .build()

    //将数据sink到文件
    linesDS.sinkTo(sink)

    env.execute()

  }

}
